<script setup lang="ts">
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useSetBackupMachine } from '@/services/pages/code/useCode'
  import { PropType, watch } from 'vue'

  const { setForm, setLoading, submit, resetForm } = useSetBackupMachine()

  defineOptions({
    name: 'SetBackupMachineModal',
  })

  const props = defineProps({
    codeId: {
      type: String,
      default: () => '',
    },
    standby: {
      type: Number as PropType<0 | 1>,
      default: () => 0,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
    resetForm()
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (!setForm.value.standby) {
      setForm.value.standby = 0
    }
    try {
      const res = await submit()
      if (res.code === 20000) {
        hideDialog()
        HMessage.success('保存成功')
        emits('update')
        return
      }

      HMessageBox.error(res.message)
    } catch (error) {
      HMessageBox.error('保存失败，请稍后重试')
    }
  }

  /**
   * 初始化
   */
  const init = () => {
    setForm.value.standby = props.standby
    if (Number(props.standby) === 0 || Number(setForm.value.standby) === 0) {
      setForm.value.standby = ''
    }

    setForm.value.id = props.codeId
  }

  watch(visible, init)
</script>

<template>
  <h-dialog
    v-model="visible"
    title="设置设备属性"
    :loading="setLoading"
    :content-padding-bottom="72"
    @close="hideDialog"
  >
    <el-form :model="setForm" inline-message label-position="top" class="modal_form_content">
      <el-form-item label="设备属性" prop="standby">
        <el-select v-model="setForm.standby" placeholder="请选择设备属性" clearable>
          <el-option :value="1" label="备用机" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="margin-top: 72px; display: flex; column-gap: 12px">
        <h-button is-modal type="primary" @click="onConfirm">保存</h-button>
        <h-button is-modal @click="hideDialog">取消</h-button>
      </div>
    </template>
  </h-dialog>
</template>
